import { defineStore } from 'pinia'
import { reactive,ref } from 'vue'
// 使用vueuse 将数据存储本地
import { useStorage } from '@vueuse/core'
import {getMenuList} from '@/api/menu'
import {getRoleIdApi} from '@/api/user'
import Layout from '@/layout/index.vue'
import {constantRoutes} from '@/router'
const modules = import.meta.glob("../../views/**/*.vue");

export const useMenuStore = defineStore('menu', {
	state:()=>({
		 collapse :false,
		 menuList: useStorage('menuList',null)
	}),
	actions:{
		async getUserMenuList(accountId){
			 // 异步获取菜单列表信息
			 return new Promise(async (resolve,reject)=>{
				let roleId;
				// 根据用户id获取角色id
				await getRoleIdApi(accountId).then((resp)=>{
					roleId = resp.data.roleId
				})
				// 根据角色Id查询菜单树
				await getMenuList(roleId).then(
				 (resp)=>{
					 let  accessedRoutes;
					  if(resp.code == 200){
						accessedRoutes = filterAsyncRoutes(resp.data.data)
						this.menuList = constantRoutes.concat(accessedRoutes)
					  }
					// 设置路由信息
					resolve(accessedRoutes)		
				 },
				 (error)=>{
					reject(error) 
				 })
			 })
		}
		
	}

})

// 过滤封装组件
export function filterAsyncRoutes(routes){
	const res = []
	routes.forEach((route)=>{
		const tmp = {...route}
		const component = tmp.component
		if(tmp.hidden=='false'){
			tmp.hidden =false
		}
		if(tmp.hidden=='true'){
			tmp.hidden =true
		}
		if(route.component){
			if(component =='Layout'){
				tmp.component = Layout
			}else{
				tmp.component =  modules[`../../views${component}.vue`]
			}
		}
		
		//判断是否有下级
			if (tmp.children && tmp.children.length > 0 ) {
					tmp.children = filterAsyncRoutes(tmp.children)
			}else{
			delete tmp.children
			delete tmp.redirect
			}
		        res.push(tmp)
	})
	 return res
}